import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtTabs} from 'taro-ui'
import {Image, View} from '@tarojs/components'
import {redbagItem} from '../../../utils/server.interface'
import {http} from '../../../utils/http'
import {GET_REDBAG, RESOURCE_URL} from '../../../constants/api'
import Redbag from './redbag/redbag'
import {user} from '../../../utils/user.service'
import {vcmonitor} from "../../../utils/tools";
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import './list.scss'

export default class List extends Component {
  state: {
    curTabIndex: number
    loadMoreStatus: "more" | "loading" | "noMore"
    redbagList: redbagItem[]
    select: any
    showLoading: boolean
  } = {
    curTabIndex: 0,
    loadMoreStatus: 'loading',
    redbagList: [],
    select: 0,
    showLoading: true
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    // const select = Taro.getCurrentInstance().router.params.select || 0
    const select = 1
    this.page = 1
    const redbagList = await this.getData(this.page)
    this.setState({redbagList, showLoading: false, select})
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      this.page++
      const redbagList: any = await this.getData(this.page)
      const old: any = this.state.redbagList
      if (redbagList) {
        this.setState({redbagList: [...old, ...redbagList]})
      }
    }
  }

  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    const {showLoading} = this.state
    if (!showLoading) {
      const redbagList = await this.getData(this.page)
      this.setState({redbagList})
    }
  }

  tabClick(index) {
    Taro.showLoading({title: '加载中...'})
    this.page = 1
    this.setState({curTabIndex: index, loadMoreStatus: 'loading', orderList: [], redbagList: []}, async () => {
      const redbagList = await this.getData(this.page)
      this.setState({redbagList})
    })
    Taro.hideLoading()
  }

  onPullDownRefresh() {
    Taro.stopPullDownRefresh()
  }

  page = 1
  tabs = [{title: '未使用', value: 0}, {title: '已使用', value: 1}, {title: '已过期', value: 99}]

  async getData(page) {
    Taro.showLoading({title: '加载中...'})
    const index = this.state.curTabIndex
    const redbagList = await http.get<redbagItem[]>(GET_REDBAG, {pageNumber: page, status: this.tabs[index].value})
    if (redbagList && redbagList.length === 10) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    Taro.hideLoading()
    return redbagList || []
  }

  itemClick(item: redbagItem) {
    const {select, curTabIndex} = this.state
    if (select > 0) {
      if (!curTabIndex) {
        const pages = Taro.getCurrentPages()
        const prevPage = pages[pages.length - 2]
        if (prevPage) {
          prevPage.data.redbagId = item.id
          prevPage.data.redbag = item
          Taro.navigateBack({
            delta: 1
          })
        }
      } else {
        Taro.showToast({title: `您不能使用${curTabIndex == 1 ? '已使用' : '已过期'}的红包`, icon: "none"})
      }
    }
  }

  render() {
    const {curTabIndex, redbagList, select} = this.state
    return (
      <View className='redbag-list-root-wrapper'>
        <View className='redbag-list-root'>
          <GzhAuth />
          <AtTabs tabList={this.tabs} current={curTabIndex} onClick={this.tabClick.bind(this)} />
          {!!select && <View className='look'>目前可用最大红包￥{select},请选择适合的红包进行抵扣。</View>}
          <View style='height: 10px' />
          {redbagList && redbagList.map(item => <View className='item' key={item.id}
            hoverClass={`${select && 'hover'}`}
            onClick={this.itemClick.bind(this, item)}
          >
            <Redbag mode='redbag' name='通用红包' total={item.amount} memo={item.memo} status={curTabIndex} />
          </View>)}
          {redbagList.length <= 0 && <View className='listNull'>
            <Image src={`${RESOURCE_URL}/upload/images/20211112/1636708674979_153.png`} mode='widthFix' />
            <View className='text'>暂无数据</View>
          </View>}
        </View>
      </View>
    )
  }
}
